package com.bang.study.query;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FieldValueFactorFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName: DismaxSearch
 * @author: BANG
 * @Date: 2020/01/15 09:54
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 */
public class FuzzySearch {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder().build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );


        QueryBuilder queryBuilder=QueryBuilders.fuzzyQuery("text","surprize").fuzziness(Fuzziness.TWO);
        SearchResponse searchResponse = client.prepareSearch("is_index").setTypes("my_type")
                .setQuery(queryBuilder)
                .get();

        for (SearchHit searchHit : searchResponse.getHits().getHits()) {
            float score = searchHit.getScore();
            System.err.println(score);
            System.err.println(searchHit.getSource());
            System.err.println("===============================");
        }
        System.err.println("-----------------------------------------");

        searchResponse=client.prepareSearch("is_index").setTypes("my_type")
                .setQuery(QueryBuilders.matchQuery("text","SURPIZE ME").fuzziness(Fuzziness.AUTO).operator(Operator.AND))
                .get();
        for (SearchHit searchHit : searchResponse.getHits().getHits()) {
            float score = searchHit.getScore();
            System.err.println(score);
            System.err.println(searchHit.getSource());
            System.err.println("===============================");
        }
        System.err.println("-----------------------------------------");
        client.close();
    }
}
